package com.combetter.changxing.http.base;

import android.app.Activity;


import com.combetter.changxing.http.dialog.LoadingDialog;
import com.combetter.changxing.utils.ToastUtils;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @name: XXX
 * @description: ${description}
 * @author: qintao
 * @create: 2018-06-02
 **/
public class HttpUtil {

    //缓存时间单位：秒，分，时，天
    public static long SECOND = 1000L;
    public static long MINUTE = 60 * SECOND;
    public static long HOUR = 60 * MINUTE;
    public static long DAY = 24 * HOUR;

    private Activity activity;
    private boolean showLoading;
    private Observable observable;

    public HttpUtil() {
    }

    public HttpUtil(Activity activity, boolean showLoading) {
        this.activity = activity;
        this.showLoading = showLoading;
    }

    /**
     * 被观察者
     *
     * @param observable
     * @return
     */
    public HttpUtil api(Observable observable) {
        this.observable = observable;
        return this;
    }

    /**
     * 启动网络请求(Activity请使用该方法)
     *
     * @param observer 观察者
     */
    public void call(Observer observer) {
        if (activity != null && showLoading) {//对话框控制
            final LoadingDialog loadingDialog = new LoadingDialog(activity);
            loadingDialog.setCanceledOnTouchOutside(false);
            observable = observable
                    //订阅时显示对话框
                    .doOnSubscribe(disposable -> activity.runOnUiThread(() -> {
                        if (showLoading) loadingDialog.show();
                    }))
                    .doOnError(throwable -> loadingDialog.dismiss())
                    //完成后隐藏并销毁对话框
                    .doOnComplete(() -> {
                        if (!activity.isDestroyed()) {
                            loadingDialog.dismiss();
                        }
                    });
        }
        call(observer, observable);
    }

    /**
     * 启动网络请求（Application,Service请使用该方法，activity不弹加载对话框，也可以使用该方法）
     *
     * @param observable 订阅事件
     * @param observer   观察者
     */
    private void call(Observer observer, Observable observable) {
        observable = observable
                //在IO线程执行订阅的事件
                .subscribeOn(Schedulers.io())  //订阅者
                //在UI线程进行观察
                .observeOn(AndroidSchedulers.mainThread());

        //开始订阅
        observable.subscribe(observer);
    }

    private void cancel() {
//        ToastUtils.showShort("已取消网络请求");
        observable.unsubscribeOn(Schedulers.io());
    }

    //清除cookies
    public static void clearCookies() {
//        SPUtils.getInstance().remove("cookies");
    }
}
